var express = require('express')
var fs = require('fs')
var path = require('path')
var userRouter = express.Router()
var jwt = require('jsonwebtoken')

// 请求数据渲染页面，分页
userRouter.get('/list', (req, res) => {
    var { page, count } = req.query
    var file = path.join(__dirname, '../json/obj.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var ye = Math.ceil(arr.length / count)
    var arr1 = arr.slice((page - 1) * count, page * count)
    res.send({ code: 200, msg: '请求成功！', list: arr1, li: ye })
})
// 内容搜索
userRouter.get('/search', (req, res) => {
    var { searchkey } = req.query
    var file = path.join(__dirname, '../json/obj.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var arr2 = arr.filter((item) => {
        return item.name.includes(searchkey)
    })
    res.send({ code: 200, msg: '查询成功!', list: arr2 })
})
// 登录请求
userRouter.post('/login', (req, res) => {
    var { phone, pass } = req.body
    var file = path.join(__dirname, '../json/obj.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var a = arr.findIndex((item) => {
        return item.phone == phone && item.pass == pass
    })
    if (a == -1) {
        res.send({ code: 400, msg: '登陆失败!' });
    } else {
        const token = jwt.sign({ phone }, '1234', { algorithm: 'HS256', expiresIn: 60 })
        res.send({ code: 200, msg: '登陆成功!', userinfo: arr[a], token });
    }
})
// 注册请求
userRouter.post('/register', (req, res) => {
    var { phone } = req.body
    var file = path.join(__dirname, '../json/obj.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var i = arr.findIndex((item) => {
        return item.phone == phone
    })
    if (i == -1) {
        arr.push({ ...req.body, zu: "编辑组", zhuang: true, guan: true })
        fs.writeFileSync(file, JSON.stringify(arr), 'utf-8')
        res.send({ code: 200, msg: '注册成功！' })
    } else {
        res.send({ code: 400, msg: '该手机号已注册，注册失败' })
    }
})
// 删除请求
userRouter.post('/delete', (req, res) => {
    var { phone } = req.body
    var file = path.join(__dirname, '../json/obj.json')
    var arr = fs.readFileSync(file)
    arr = arr.toString() ? JSON.parse(arr) : []
    var i = arr.findIndex((item) => {
        return item.phone == phone
    })
    if (i == -1) {
        res.send({ code: 400, msg: '删除失败！' })
    } else {
        arr.splice(i, 1)
        fs.writeFileSync(file, JSON.stringify(arr), 'utf-8')
        var arr1 = arr.slice(0, 3)
        res.send({ code: 200, msg: '删除成功！', list: arr1 })
    }
})
module.exports = userRouter